#include "rosNodeManager.h"

/*
dataInfo 格式
{
    SN_ID: "2023_DXY";
    publisher_pid: 1234,
    publisher_port: 50660,
    subscribe_pids: [1234, 4321, ...],
    subscribe_ports: [50661, 50662, ...],
    topic_name: "/SN_ID/someoneTopic",
    state:  {
                abc: 0,
                xyz: 1
            }
}
*/

using namespace std;
using namespace easyWebServer;

namespace dxy::easyWebServer
{

RosNodeManager & RosNodeManager::getInstance()
{
    static RosNodeManager instance;
    return instance;
}

std::vector<std::string> RosNodeManager::getAllNode()
{
    return RedisConnector::getInstance().keys();
}

int RosNodeManager::killNode(const std::string & SN_ID, bool isBlock)
{
    string reply = RedisConnector::getInstance().get(SN_ID);
    if(reply == "") return -1;
    Json replyJson;
    replyJson.parse(reply);
    pid_t pid = (pid_t)replyJson["publisher_pid"].asInt();
    m_futrue = async(launch::async, [=] () {
        waitpid(pid, NULL, 0);
    });
    kill(pid, SIGKILL);
    RedisConnector::getInstance().del(SN_ID);
    if(isBlock == true)
    {
        m_futrue.get();
    }
    return 0;
}

pid_t RosNodeManager::createPublicRosNode(const std::string & SN_ID, const uint16_t port)
{
    pid_t pid = fork();
    if(pid < 0)
    {
        error("fork error");
    }
    else if(pid == 0)
    {
        execl(  (Singleton<Json>::getInstance()["ros_root"].asString() + "/devel/lib/lvpublisher_pkg/lvpublisher_pkg_node").c_str(), 
                "lvpublisher_pkg_node",
                SN_ID.c_str(),
                to_string(port).c_str(),
                Singleton<Json>::getInstance()["host"].asString().c_str(),
                to_string(Singleton<Json>::getInstance()["port"].asInt()).c_str(),
                NULL);
    }
    return pid;
}

RosNodeManager::RosNodeManager()
{

}

RosNodeManager::~RosNodeManager()
{

}

}

